import { User } from '../../types';
import { UserRepository } from '../../repositories/system/UserRepository';
import { HttpError } from '../../exceptions/HttpError';
export class UserService {
  private userRepository: UserRepository;
  constructor() {
    this.userRepository = new UserRepository();
  }
  
  // 获取所有用户
  async getAllUsers(): Promise<User[]> {
    try {
      return await this.userRepository.findAll();
    } catch (error: any) {
      if (error instanceof HttpError) throw error;
      throw HttpError.internalServerError(`获取用户列表失败: ${error.message}`);
    }
  }

  // 根据ID获取用户
  async getUserById(id: string): Promise<User | null> {
    try {
      return await this.userRepository.findById(id);
    } catch (error: any) {
      if (error instanceof HttpError) throw error;
      throw HttpError.internalServerError(`获取用户信息失败: ${error.message}`);
    }
  }

  // 创建用户
  async createUser(userData: Partial<User>): Promise<User> {
    try {
      return await this.userRepository.create(userData);
    } catch (error: any) {
      if (error instanceof HttpError) throw error;
      throw HttpError.internalServerError(`创建用户失败3: ${error.message}`);
    }
  }

  // 更新用户
  async updateUser(id: string, userData: Partial<User>): Promise<User | null> {
    try {
      return await this.userRepository.update(id, userData);
    } catch (error: any) {
      if (error instanceof HttpError) throw error;
      throw HttpError.internalServerError(`更新用户失败: ${error.message}`);
    }
  }

  // 删除用户
  async deleteUser(id: string): Promise<boolean> {
    try {
      return await this.userRepository.delete(id);
    } catch (error: any) {
      if (error instanceof HttpError) throw error;
      throw HttpError.internalServerError(`删除用户失败: ${error.message}`);
    }
  }

  // 根据邮箱查找用户（用于认证）
  async getUserByEmail(email: string): Promise<User | null> {
    try {
      return await this.userRepository.findByEmail(email);
    } catch (error: any) {
      if (error instanceof HttpError) throw error;
      throw HttpError.internalServerError(`查找用户失败: ${error.message}`);
    }
  }

  // 获取用户数量
  async getUserCount(): Promise<number> {
    try {
      return await this.userRepository.count();
    } catch (error: any) {
      if (error instanceof HttpError) throw error;
      throw HttpError.internalServerError(`统计用户数量失败: ${error.message}`);
    }
  }

  // 分页查询用户
  async getUsersWithPagination(page: number = 1, limit: number = 10): Promise<{ list: User[], total: number, pages: number }> {
    try {
      return await this.userRepository.findWithPagination(page, limit);
    } catch (error: any) {
      if (error instanceof HttpError) throw error;
      throw HttpError.internalServerError(`分页查询用户失败: ${error.message}`);
    }
  }
}